use std::sync::Arc;
use tokio::sync::RwLock;
use librqbit::*;
use serde::{Serialize, Deserialize};
use std::path::Path;
use tauri::{AppHandle, Emitter};

use crate::download_manager::{DownloadTask, DownloadStatus};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TorrentProgress {
    pub downloaded_pieces: Vec<bool>,
    pub piece_size: u64,
    pub total_pieces: usize,
    pub connected_peers: u32,
    pub download_speed: f64,
    pub upload_speed: f64,
}

pub async fn download_magnet(
    app_handle: AppHandle,
    task: Arc<DownloadTask>,
) -> Result<String, String> {

    let session = Session::new(task.path.clone().into()).await
        .map_err(|e| format!("创建会话失败: {}", e))?;
    let managed_torrent_handle = session.add_torrent(
       AddTorrent::from_url(&task.url),
       None // options
    ).await
        .map_err(|e| format!("添加种子失败: {}", e))?
        .into_handle()
        .ok_or_else(|| format!("获取种子句柄失败"))?;

    // 获取TorrentStats
    let stats = managed_torrent_handle.stats();

    let total_size = stats.total_bytes;

    {
        let mut progress = task.progress.write().await;
        progress.total_size = total_size;
        progress.status = DownloadStatus::Downloading;
    }

    while stats.file_progress.iter().sum::<u64>() < 1 {
        // 检查是否需要暂停或取消
        let cancel_flag = task.cancel_flag.read().await;
        if *cancel_flag {
            session.pause(&managed_torrent_handle)
                .await
                .map_err(|e| format!("暂停种子失败: {}", e))?;
            return Ok("下载已暂停".to_string());
        }

        let downloaded = stats.progress_bytes;
        // let peers = stats.connected_peers;
        // let down_speed = stats.download_speed;
        // let up_speed = stats.upload_speed;

        let mut progress = task.progress.write().await;
        progress.downloaded_size = downloaded;
        progress.progress = (downloaded as f64 / total_size as f64) * 100.0;

        // 发送进度更新
        let progress_clone = progress.clone();
        drop(progress);
        app_handle
            .emit("download_progress", progress_clone)
            .map_err(|e| e.to_string())?;

        tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
    }

    {
        let mut progress = task.progress.write().await;
        progress.status = DownloadStatus::Completed;
        progress.progress = 100.0;

        let progress_clone = progress.clone();
        drop(progress);
        app_handle
            .emit("download_progress", progress_clone)
            .map_err(|e| e.to_string())?;
    }

    Ok("下载完成".to_string())
}

pub async fn download_torrent(
    app_handle: AppHandle,
    task: Arc<DownloadTask>,
    torrent_path: String,
) -> Result<String, String> {

    let session = Session::new(task.path.clone().into()).await
        .map_err(|e| format!("创建会话失败: {}", e))?;
    let managed_torrent_handle = session.add_torrent(
       AddTorrent::from_local_filename(&torrent_path)
           .map_err(|e| format!("加载种子文件失败: {}", e))?,
       None // options
    ).await
        .map_err(|e| format!("添加种子失败: {}", e))?
        .into_handle()
        .ok_or_else(|| format!("获取种子句柄失败"))?;

    // 获取TorrentStats
    let stats = managed_torrent_handle.stats();

    let total_size = stats.total_bytes;
    // let piece_size = stats.piece_length as u64;
    // let total_pieces = stats.pieces.len();

    {
        let mut progress = task.progress.write().await;
        progress.total_size = total_size;
        progress.status = DownloadStatus::Downloading;
    }

    while stats.file_progress.iter().sum::<u64>() < 1 {
        // 检查是否需要暂停或取消
        let cancel_flag = task.cancel_flag.read().await;
        if *cancel_flag {
            session.pause(&managed_torrent_handle)
                .await
                .map_err(|e| format!("暂停种子失败: {}", e))?;
            return Ok("下载已暂停".to_string());
        }

        let downloaded = stats.progress_bytes;
        // let peers = stats.connected_peers;
        // let down_speed = stats.download_speed;
        // let up_speed = stats.upload_speed;

        let mut progress = task.progress.write().await;
        progress.downloaded_size = downloaded;
        progress.progress = (downloaded as f64 / total_size as f64) * 100.0;

        // 发送进度更新
        let progress_clone = progress.clone();
        drop(progress);
        app_handle
            .emit("download_progress", progress_clone)
            .map_err(|e| e.to_string())?;

        tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
    }

    {
        let mut progress = task.progress.write().await;
        progress.status = DownloadStatus::Completed;
        progress.progress = 100.0;

        let progress_clone = progress.clone();
        drop(progress);
        app_handle
            .emit("download_progress", progress_clone)
            .map_err(|e| e.to_string())?;
    }

    Ok("下载完成".to_string())
}